<?php

class DoctrineValidatorAccount extends sfValidatorBase
{
  public function configure($option = array(), $message = array())
  {
    $this->addOption('email')
      ->addOption('password');

    $this->addMessage('email', '此Email并未注册')
      ->addMessage('password', '密码不正确')
      ->setMessage('invalid',  '需要的参数不完整');
  }

  protected function doClean($value)
  {
    $value['email'] = trim($value['email']);
    $value['password'] = trim($value['password']);

    if (!$value['email'] || !$value['password'])
    {
      throw new sfValidatorError($this, 'invalid');
    }

    $account = Doctrine::getTable('Application')->findOneByEmail($value['email']);
    if ($account)
    {
      if ($account->getPassword() !== sha1('n' . $value['password'] . 'b'))
      {
        throw new sfValidatorError($this, 'password');
      }
    }
    else
    {
      throw new sfValidatorError($this, 'email');
    }

    $user = sfContext::getInstance()->getUser();
    $user->setAuthenticated(true);
    $user->setAttribute('id', $account->getId());
    $user->setAttribute('account', $account->getName());

    return $value;
  }
}
